package com.csj.DesignPattern.spring.customSpring.framework;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class MutablePropertyValues implements Iterable<PropertyValue>{

    private final List<PropertyValue> propertyValues;

    public MutablePropertyValues() {
        propertyValues = new ArrayList<>();
    }

    public MutablePropertyValues(List<PropertyValue> propertyValues) {
        if (propertyValues == null) {
            this.propertyValues = new ArrayList<>();
        }
        else {
            this.propertyValues = propertyValues;
        }
    }

    public PropertyValue[] getPropertyValues() {
        return propertyValues.toArray(new PropertyValue[0]);
    }

    public PropertyValue getPropertyValues(String name) {
        for (PropertyValue propertyValue : propertyValues) {
            if (propertyValue.getName().equals(name)) {
                return propertyValue;
            }
        }
        return null;
    }

    public boolean isEmpty() {
        return propertyValues.isEmpty();
    }

    public MutablePropertyValues addProperty(PropertyValue pvs) {
        for (int i = 0; i < propertyValues.size(); i++) {
            PropertyValue currentpsv = propertyValues.get(i);
            if (currentpsv.getName().equals(pvs.getName())) {
                propertyValues.set(i, pvs);
                return this;
            }
        }
        this.propertyValues.add(pvs);
        return this;
    }

    public boolean contains(String name) {
        return getPropertyValues(name) != null;
    }

    @Override
    public Iterator<PropertyValue> iterator() {
        return propertyValues.iterator();
    }
}
